package cn.com.template.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

	@RequestMapping("/getTestData")
	public String root(HttpServletResponse response, HttpServletRequest request) {
		System.out.println("getTestData called!");
		return null;
	}
	
	@RequestMapping(value = "/searchByZoe", method = RequestMethod.POST)  
	@ResponseBody  
	public JSONResponse search(@RequestBody JSONParam[] params){  
		System.out.println("searchByZoe called!");
	    HashMap<String, String> paramMap = convertToMap(params);  
	    
	    String sEcho = paramMap.get("sEcho");  
	    String searchName = paramMap.get("searchName");  
	    int start = Integer.parseInt(paramMap.get("iDisplayStart"));  
	    int length = Integer.parseInt(paramMap.get("iDisplayLength"));  
	      
	    System.out.println(sEcho+"\t"+searchName+"\t"+start+"\t"+length);
	    List<Object> resultLst = search(searchName, start, length);  
	    int count = resultLst.size(); 
	    System.out.println(count); 
	    String[][] data = new String[count][];  
	    PersonEntity p = null;
	    for(int i=0; i<count; i++) {  
	    	p = (PersonEntity)resultLst.get(i);  
	        data[i] = getPersonDataArr(p);
	    }  
	      
	    return successed(new DataTableReturnEntity(20, 20, sEcho, data)); 
	}  

	protected HashMap<String, String> convertToMap(JSONParam[] params) {
		HashMap<String, String> map = new HashMap<String, String>();
		for (JSONParam param : params) {
			map.put(param.getName(), param.getValue());
		}
		return map;
	}
	
	private List<Object> search(String customerName, int start, int length){
		 List<Object> resultLst = new ArrayList<Object>();
		 for(int i = 0; i< 20; i++){
			 resultLst.add(new PersonEntity("zoe"+i, i+1, "boy"));
		 }
		 return resultLst.subList(start, start+length); 
	}
	
	protected JSONResponse successed(Object obj) {
		JSONResponse ret = new JSONResponse();
		ret.setSuccessed(true);
		ret.setReturnObject(obj);
		return ret;
	}
	
	private String[] getPersonDataArr(PersonEntity p){
		String[] dataArr = new String[3];
		dataArr[0] = p.getName();
		dataArr[1] = p.getSex();
		dataArr[2] = p.getAge()+"";
		return dataArr;
	}
}
